<template>
  <div class="data-form activity-form" v-loading.fullscreen.lock="loading">
    <el-form label-width="auto" size="medium">
      <el-form-item label="类型名称">
        <el-input v-model="activityTypeForm.activityTypeName" class="form-input">
        </el-input>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="activityTypeForm.status" class="form-input">
          <el-option v-for="item in statusList" :key="item.value" :value="item.value" :label="item.label">
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>

    <div style="text-align:center">
      <el-button size="medium" type="primary" @click="saveActivity">
        <span v-if="type==='add'">新增</span>
        <span v-else>修改</span>
      </el-button>
    </div>
  </div>
</template>

<script>
  import GoodsApi from 'services/goodsApi';

  import ActivityTypeForm from 'models/goods/activityTypeForm';

  export default {
    props: {
      activity: {
        type: Object,
        default () {
          return null
        }
      },
      type: {
        type: String,
        default: 'add'
      }
    },

    data() {
      let activityTypeForm;
      if (this.type === 'add') {
        activityTypeForm = new ActivityTypeForm();
      } else {
        activityTypeForm = _.cloneDeep(this.activity);
      }
      return {
        loading: false,
        activityTypeForm,
        statusList: this.i18n.getDropDown('goods.activityType.status', [1, 0])
      };
    },

    methods: {
      saveActivity() {
        let activityTypeForm = this.activityTypeForm;
        let code = activityTypeForm.checkValid();
        if (code !== '') {
          let msg = this.i18n.getMsg(`goods.activityType.error.${code}`);
          this.$message(msg);
          return;
        }

        if (this.type === 'add') {
          this.addActivity(activityTypeForm);
        } else {
          this.updateActivity(activityTypeForm);
        }
      },

      addActivity(activityTypeForm) {
        this.loading = true;
        GoodsApi.addActivity(activityTypeForm).then(() => {
          this.loading = false;
          this.$alert('活动类型新增成功', '信息', {
            callback: () => {
              this.$emit('save-success');
            }
          });
        }).catch(() => {
          this.loading = false;
        });
      },

      updateActivity(activityTypeForm) {
        this.loading = true;
        GoodsApi.updateActivity(activityTypeForm).then(() => {
          this.loading = false;
          this.$alert('活动类型修改成功', '信息', {
            callback: () => {
              this.$emit('save-success');
            }
          });
        }).catch(() => {
          this.loading = false;
        });
      }
    }
  };

</script>

<style lang="scss" scoped>
  @import '~viewStyle/dataForm';

</style>
